<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreReplyRequest;
use App\Http\Requests\UpdateReplyRequest;
use App\Models\Post;
use App\Models\Reply;
use App\Services\ReplyService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class ReplyController extends Controller
{
    public function __construct(
        private ReplyService $replyService
    ) {}

    /**
     * 获取帖子回复列表
     */
    public function index(Request $request, Post $post): Response
    {
        $replies = $this->replyService->getRepliesList($post, $request->user());

        return Inertia::render('Posts/Show', [
            'post' => $post->load(['user', 'bar']),
            'replies' => $replies,
        ]);
    }

    /**
     * 创建回复
     */
    public function store(StoreReplyRequest $request, Post $post): RedirectResponse
    {
        try {
            $reply = $this->replyService->createReply(
                $post,
                $request->user(),
                $request->validated()
            );

            return back()->with('success', '回复成功！');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * 更新回复
     */
    public function update(UpdateReplyRequest $request, Reply $reply): RedirectResponse
    {
        try {
            $this->replyService->updateReply(
                $reply,
                $request->user(),
                $request->validated()
            );

            return back()->with('success', '回复更新成功！');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * 删除回复
     */
    public function destroy(Reply $reply): RedirectResponse
    {
        $this->authorize('delete', $reply);

        try {
            $this->replyService->deleteReply($reply, request()->user());

            return back()->with('success', '回复已删除');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * 点赞/取消点赞回复
     */
    public function toggleLike(Request $request, Reply $reply): RedirectResponse
    {
        try {
            $isLiked = $this->replyService->toggleLike($reply, $request->user());

            return back()->with('success', $isLiked ? '已点赞' : '已取消点赞');
        } catch (\Exception $e) {
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }
}
